const { ipcRenderer } = require('electron');
const EmailService = require('./email-service');
const path = require('path');

// 这里应该从某个安全的地方获取用户凭证
const emailService = new EmailService('example@mail.com', 'BLQeEqEm3KV8RK9d');

document.addEventListener('DOMContentLoaded', () => {
    const toInput = document.getElementById('to');
    const subjectInput = document.getElementById('subject');
    const bodyTextarea = document.getElementById('body');
    const attachmentInput = document.getElementById('attachment');
    const attachmentList = document.getElementById('attachment-list');
    const sendBtn = document.getElementById('send-btn');

    let attachments = [];

    attachmentInput.addEventListener('change', (event) => {
        const files = event.target.files;
        for (let file of files) {
            attachments.push(file.path);
            const listItem = document.createElement('div');
            listItem.textContent = file.name;
            attachmentList.appendChild(listItem);
        }
    });

    ipcRenderer.on('reply-to-email', (event, email) => {
        toInput.value = email.from;
        subjectInput.value = `Re: ${email.subject}`;
        bodyTextarea.value = `\n\n-------- 原始邮件 --------\n${email.text}`;
    });

    sendBtn.addEventListener('click', () => {
        const to = toInput.value;
        const subject = subjectInput.value;
        const body = bodyTextarea.value;

        if (to && subject && body) {
            emailService.sendEmail(to, subject, body)
                .then(() => {
                    alert('邮件发送成功！');
                    window.close();
                })
                .catch(error => {
                    console.error('发送邮件失败:', error);
                    alert('发送邮件失败，请重试。');
                });
        } else {
            alert('请填写所有字段。');
        }
    });
});
